//
//  EFAAppVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAAppVC.h"
#import "EFAAppCCell.h"
#import "MBProgressHUD+XDPrompt.h"
#import "EFAReportVC.h"
#import "AppDelegate.h"
#import "EFAPjtManagerVC.h"
#import "EFAModel.h"
#import "EFANoticeVC.h"
#import "EFAMaintenanceVC.h"
#import "EFAAlarmVC.h"
#import "EFAPjtMgrWithRoleVC.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFADangerVC.h"
#import "ReportVC.h"
#import "ReportProjectListVC.h"
#import "ReportListVC.h"

@interface EFAAppVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate,UINavigationControllerDelegate>
@property (weak,   nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) UIImageView *headerImgView;
@property (strong, nonatomic) NSArray *dataArray;
@end

static NSString *const kReuseCellId = @"EFAAppCCell";
static CGFloat const kHeaderHeight = 390.0;
static CGFloat const kHeaderWidth = 750.0;

@implementation EFAAppVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"应用";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    // 设置导航控制器的代理为self
    self.navigationController.delegate = self;
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.alwaysBounceVertical = YES;
    // 顶部图片放大
    [self.collectionView insertSubview:self.headerImgView atIndex:0];
    CGFloat height = CGRectGetWidth([UIScreen mainScreen].bounds) * kHeaderHeight / kHeaderWidth;
    self.collectionView.contentInset = UIEdgeInsetsMake(height, 0, 0, 0);
    
    // 下拉刷新
//    self.collectionView.mj_header = self.mj_header;
//    self.collectionView.mj_footer = self.mj_footer;
//    self.collectionView.emptyDataSetDelegate = self;
//    self.collectionView.emptyDataSetSource = self;
    // 请求数据
//    [self.collectionView.mj_header beginRefreshing];
    
    ///< 请求用户角色
    [self requestRefreshUserInfo];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    // 判断要显示的控制器是否是自己
    BOOL isSelf = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isSelf animated:YES];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    EFAAppCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.item < self.dataArray.count) {
        NSDictionary *dic = self.dataArray[indexPath.item];
        cell.iconImgView.image = [UIImage imageNamed:dic[@"imgName"]];
        cell.titleLabel.text = dic[@"title"];
    }
    return cell;
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 110.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*1) / 3.0;
//    CGFloat height = width * 220.0 / 250.0;
    return CGSizeMake(width, width);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item < self.dataArray.count) {
        NSDictionary *dic = self.dataArray[indexPath.item];
        NSString *title = dic[@"title"];
        if ([title isEqualToString:@"公告"]) {
            [self jumpToNotice];
        } else if ([title isEqualToString:@"报表"]) {
            [self jumpToReport];
        } else if ([title isEqualToString:@"项目管理"]) {
            [self jumpToPjtManager];
        } else if ([title isEqualToString:@"维护记录"]) {
            [self jumpToMaintenance];
        } else if ([title isEqualToString:@"隐患曝光"]) {
            [self jumpToDanger];
        } else if ([title isEqualToString:@"报警处理"]) {
            [self jumpToAlarm];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"功能维护中"];
        }
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat headerHeight = CGRectGetWidth([UIScreen mainScreen].bounds) * kHeaderHeight / kHeaderWidth;
    CGFloat offsetH = -headerHeight - offsetY;
    
    if (offsetH < 0) return;
    
    CGRect frame = self.headerImgView.frame;
    frame.size.height = headerHeight + offsetH;
    frame.origin.y = -headerHeight - offsetH;
    self.headerImgView.frame = frame;
}

#pragma mark - event response

#pragma mark - private methods
- (void)jumpToNotice {
    EFANoticeVC *vc = [[EFANoticeVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)jumpToReport {
//    EFAPjtManagerVC *vc = [[EFAPjtManagerVC alloc] initWithViewType:EFAPjtManagerVCTypeReport];
//    EFAReportVC *vc = [[EFAReportVC alloc] init];
    
    ReportVC *vc = [[ReportVC alloc]init];
//    ReportProjectListVC  *vc = [[ReportProjectListVC alloc]init];
//    ReportListVC *vc = [[ReportListVC alloc]init];
    [self showViewController:vc sender:nil];
}
- (void)jumpToPjtManager {
//    EFAPjtMgrWithRoleVC *vc = [[EFAPjtMgrWithRoleVC alloc] initWithViewType:EFAPjtMgrRoleTypeOwn];
    EFAPjtMgrWithRoleVC *vc = [[EFAPjtMgrWithRoleVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)jumpToMaintenance {
    EFAMaintenanceVC *vc = [[EFAMaintenanceVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)jumpToAlarm {
    EFAAlarmVC *vc = [[EFAAlarmVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)jumpToDanger {
    EFADangerVC *vc = [[EFADangerVC alloc] init];
    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    // 尾部加载更多的显示
//    if (self.userList.totalLoad) {
//        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
//    } else {
//        [self.collectionView.mj_footer resetNoMoreData];
//    }
    
    [self.collectionView reloadData];
}

//- (void)collectionViewEndRefresh:(BOOL)isHeader {
//    NSLog(@"停止刷新是否是头部---%zd", isHeader);
//    if (isHeader) {
//        [self.collectionView.mj_header endRefreshing];
//    } else {
//        [self.collectionView.mj_footer endRefreshing];
//    }
//}
//
//- (void)collectionViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
//    [self requestUserListWithHeader:isHeader];
//}
//
//- (KABMineUserList *)userListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
//    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
//        return self.userList;
//    }
//    
//    KABMineUserList *temp = [KABMineUserList yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
//    if (!temp) {
//        return self.userList;
//    }
//    
//    if (AddMore && self.userList) {
//        [self.userList addMoreWithData:temp];
//    } else {
//        self.userList = temp;
//    }
//    return self.userList;
//}

#pragma mark - network request
- (void)requestRefreshUserInfo {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineUserCenter] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求用户信息返回：%@", responseObject);
        [[EFAModel sharedInstance] refreshUserInfoWithDictionary:responseObject];
        self.dataArray = [self refreshDataArray];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求用户信息失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIImageView *)headerImgView {
    if (!_headerImgView) {
        _headerImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"app_header"]];
        CGFloat width = CGRectGetWidth([UIScreen mainScreen].bounds);
        _headerImgView.frame = CGRectMake(0, 0, width, -width * kHeaderHeight / kHeaderWidth);
        _headerImgView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _headerImgView;
}
- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [self refreshDataArray];
    }
    return _dataArray;
}
- (NSArray *)refreshDataArray {
    BOOL isReview = ((AppDelegate *)[UIApplication sharedApplication].delegate).isReview;
    BOOL isNormalUser = ([EFAModel sharedInstance].loginInfo.user_info.efairyrole_level == EFALoginUserRoleNormal);
    NSArray *temp = nil;
    if (isReview) {
        if (isNormalUser) {
            temp = @[@{@"imgName" : @"app_notice",
                       @"title" : @"公告"},
                     @{@"imgName" : @"app_report",
                       @"title" : @"报表"},
                     @{@"imgName" : @"app_alarm",
                       @"title" : @"报警处理"},
                     @{@"imgName" : @"app_maintenance",
                       @"title" : @"维护记录"},
                     @{@"imgName" : @"app_danger",
                       @"title" : @"隐患曝光"}];
        } else {
            temp = @[@{@"imgName" : @"app_notice",
                       @"title" : @"公告"},
                     @{@"imgName" : @"app_report",
                       @"title" : @"报表"},
                     @{@"imgName" : @"app_alarm",
                       @"title" : @"报警处理"},
                     @{@"imgName" : @"app_maintenance",
                       @"title" : @"维护记录"},
                     @{@"imgName" : @"app_danger",
                       @"title" : @"隐患曝光"},
                     @{@"imgName" : @"app_project",
                       @"title" : @"项目管理"}];
        }
    } else {
        if (isNormalUser) {
            temp = @[@{@"imgName" : @"app_notice",
                       @"title" : @"公告"},
                     @{@"imgName" : @"app_report",
                       @"title" : @"报表"},
                     @{@"imgName" : @"app_alarm",
                       @"title" : @"报警处理"},
                     @{@"imgName" : @"app_maintenance",
                       @"title" : @"维护记录"},
                     @{@"imgName" : @"app_danger",
                       @"title" : @"隐患曝光"},
                     @{@"imgName" : @"app_payment",
                       @"title" : @"用户缴费"}];
        } else {
            temp = @[@{@"imgName" : @"app_notice",
                       @"title" : @"公告"},
                     @{@"imgName" : @"app_report",
                       @"title" : @"报表"},
                     @{@"imgName" : @"app_alarm",
                       @"title" : @"报警处理"},
                     @{@"imgName" : @"app_maintenance",
                       @"title" : @"维护记录"},
                     @{@"imgName" : @"app_danger",
                       @"title" : @"隐患曝光"},
                     @{@"imgName" : @"app_project",
                       @"title" : @"项目管理"},
                     @{@"imgName" : @"app_payment",
                       @"title" : @"用户缴费"}];
        }
    }
    return temp;
}
@end
